import { Animated, ScrollView, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { CommonConfig, windowWidth } from "../util";
import { useCallback, useRef, useState } from "react";
import { useFocusEffect } from "@react-navigation/native";
import { DictType } from "../util/publicType";

interface PropType {
  data?: Array<DictType>;
  tabChange: (v: number) => void;
}

const Index = ({ data = [{ id: "1", name: "测试" }, { id: "2", name: "测试" }], tabChange }: PropType) => {
    // 当前tab
    const tabEle = useRef<Text | null>(null);
    // 最外层元素
    const boxEle = useRef<View | null>(null);
    // 初始选择索引
    const [index, setIndex] = useState<number>(0);
    // 列表组件
    const scrollEle = useRef<null | ScrollView>(null);
    // 当前滚动的距离
    const [scrollviewX, setScrollviewX] = useState<number>(0);
    // 下划线宽度以及位置
    const [lineStyle, setLineStyle] = useState<{ left: number, width: number }>({
      width: 0,
      left: 0
    });

    // 动画
    const leftAnim = useRef(new Animated.Value(lineStyle.left)).current;

    // 更新view和底线
    const updateStyle = (scrollResult: number, lineResult: { width: number, pageX: number }, isUpdateScroll: boolean = true, isLineUpdate: boolean = true) => {
      if (isLineUpdate) {
        setLineStyle({
          left: lineResult.pageX,
          width: lineResult.width
        });
        Animated.timing(leftAnim, {
          toValue: lineResult.pageX,
          useNativeDriver: false,
          duration: 800
        }).start();
      }
      if (isUpdateScroll && scrollEle) {
        scrollEle.current?.scrollTo({
          x: scrollResult,
          y: 0
        });
      }
    };
    // 原本的值
    useFocusEffect(useCallback(() => {
      // 已获取焦点
      setTimeout(() => {
        if (tabEle) {
          // 当前点击项的位置信息
          tabEle?.current?.measure((left: number, top: number, width: number, height: number, pageX: number, pageY: number) => {
            setLineStyle({
              left: pageX,
              width
            });
            // 向右移sv
            if (windowWidth - pageX <= 100) {
              // 最后一项不移动sv
              if (index !== data.length - 1) {
                return updateStyle(scrollviewX + 100, { width, pageX: pageX - 100 });
              }
              // 不移动scrollview
              return updateStyle(scrollviewX, { width, pageX }, false, true);
            }
            // 是否左移sv
            if (pageX < 100) {
              // 第一项不移动sv
              if (index !== 0) {
                return updateStyle(scrollviewX - 100, { width, pageX: pageX + 100 });
              }
              return updateStyle(scrollviewX, { width, pageX }, false, true);
            }
            //  平移line
            return updateStyle(scrollviewX, { width, pageX }, false, true);
          });
        }
      }, 0);

    }, [index,data]));

    // 初始选中索引
    const tabClick = (i: number) => {
      setIndex(i);
      tabChange(i);
    };
    return (
      <View ref={boxEle} style={{ position: "relative" }}>
        <ScrollView horizontal={true}
                    scrollEnabled={false}
                    overScrollMode="never"//不允许滚动视图
                    ref={scrollEle}
                    style={styles.box}
                    onScroll={(event) => setScrollviewX(event.nativeEvent.contentOffset.x)}
                    showsHorizontalScrollIndicator={false}
                    contentContainerStyle={data.length > 4 ? styles.scrollViewStyleMany : styles.scrollViewStyleFew}>
          {
            data.map((v, i: number) => {
              return (
                <TouchableOpacity key={v.id} onPress={() => tabClick(i)}>
                  <View style={styles.inner}>
                    <Text ref={i === index ? tabEle : null} style={styles.txt}>{v.name}</Text>
                  </View>
                </TouchableOpacity>

              );
            })
          }
        </ScrollView>
        <Animated.View style={[{ ...styles.line, width: lineStyle.width }, {
          left: leftAnim
        }]} />
      </View>
    );
  }
;

const styles = StyleSheet.create({
  box: {
    width: "100%",
    height: 36,
    flexGrow: 0
  },
  scrollViewStyleFew: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-around",
    width: "100%"
  },
  scrollViewStyleMany: {
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
    minWidth: "100%"
  },

  inner: {
    minWidth: 100,
    display: "flex",
    flexDirection: "row",
    justifyContent: "center",
    paddingTop: 3,
    paddingBottom: 3
  },
  txt: {
    fontSize: 20,
    display: "flex",
    color: "#111"
  },
  line: {
    height: 3,
    backgroundColor: CommonConfig.color,
    position: "absolute",
    bottom: 0
  }
});

export default Index;
